<template>
  <div v-if="!isSetuser" class="distribute-loading" v-loading="true"></div>
  <div v-else class="distribute">
    <div class="header">信息中心项目管理系统--绑定禅道账号</div>
    <el-form :model="form" :rules="formrules" status-icon ref="form" label-width="80px">
      <el-form-item prop="username" label="禅道账号">
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item prop="empuid" label="员工ID">
        <el-input disabled v-model="form.empuid" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div style="text-align:center">
      <el-button type="primary" :loading="btn.loading" @click="submitForm('form')">{{btn.text}}</el-button>
    </div>
  </div>
</template>

<script>
import lightApp from "@light-app/config";
import { resetRouter } from "@router";
import userAPI from "@apis/user"; //获取用户信息

function getQueryVariable(variable) {
  console.log(111)
  const data = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    data[pair[0]] = pair[1];
  }
  return data;
}

export default {
  data() {
    const validates = (rule, value, callback) => {
      if (value === "") {
        if (rule.field == "username") {
          callback(new Error("请输入禅道账号"));
        } else {
          callback(new Error("请输入员工ID"));
        }
      } else {
        callback();
      }
    };
    return {
      isSetuser: false,
      form: {
        username: "",
        empuid: ""
      },
      btn: {
        text: "提交",
        loading: false
      },
      formrules: {
        username: [{ validator: validates, trigger: ["blur", "change"] }],
        empuid: [{ validator: validates, trigger: ["blur", "change"] }]
      }
    };
  },
  beforeCreate() {
    const qv = getQueryVariable();
    // console.log(qv,"qv")
    if (qv.token) {
      localStorage.clear(); //清除之前的localStorage
      window.location.href = `${window.location.origin}${window.location.pathname}#/home?tocken=${qv.token}`;
    }

    if (this.$route.path.startsWith("/distribute") === false) {
      let tokens = localStorage.getItem("token");
      this.$router.replace({
        path: `/distribute`,
        query: {
          returnUrl: this.$route.path,
          tocken: tokens,
          ...this.$route.query
        }
      });
    }
  },
  created() {
    if (this.$route.path.startsWith("/distribute")) {
      this.init();
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.btn.loading = true;
          userAPI
            .bindUser({ tocken: this.$route.query.tocken, ...this.form })
            .then(res => {
              console.log(res, "res");
              this.init();
            })
            .catch(err => {
              console.log(err, "err");
            });
        } else {
          return false;
        }
      });
    },
    async init() {
      const ticket = this.$route.query.tocken;

      if (ticket || process.env.NODE_ENV === "development") {
        await this.loginByTicket(ticket);
      }

      const result = await this.getUserInfo(ticket);
      if (!result || !result.success) {
        localStorage.clear();
        this.btn.loading = false;
        //已绑定，但获取信息失败
        if (result.code == 2) {
          this.$router.replace(`/error?msg=${result.message}`);
          return;
        } else if (result.code == 1) {
          //未绑定禅道账号以及员工ID
          this.isSetuser = true;
          if (result.data) {
            this.form.empuid = result.data;
          }
          this.$message.error(result.message);
          return;
        }
      }
      await this.initGlobalDatas()
        .catch(() => {
          console.warn(
            "No initStore function may affects the initial rendering"
          );
        })
        .finally(() => {
          this.btn.loading = false;
          this.redirect();
        });
    },
    //获取用户信息
    getUserInfo(token) {
      return userAPI
        .getUser(token)
        .then(res => {
          this.commitUser(res);
          return { success: true };
        })
        .catch(err => {
          // console.log(err, "err");
          return {
            success: false,
            code: err.data.code,
            message: err.message,
            data: err.data.data
          };
        });
    },
    loginByTicket(ticket) {
      return this.$store.dispatch("initToken", ticket, 0);
    },
    commitUser(res) {
      const user = {
        id: res.id,
        name: res.realname,
        empuid: res.empuid,
        nickname: res.nickname,
        is_admin: res.is_admin
      };

      this.$store.commit("setUser", user);
    },
    initGlobalDatas() {
      this.$store.commit("setConfig", lightApp);
      resetRouter();
      return this.$store.dispatch(`lightApp/initStore`);
    },
    redirect() {
      const returnUrl = this.$route.query.returnUrl;
      let path = !returnUrl ? "/home" : returnUrl;

      if (path === "/") {
        path = "/home";
      }

      const query = { ...this.$route.query };
      delete query.returnUrl;
      delete query.token;

      this.$router.replace({ path, query });
    }
  }
};
</script>

<style scoped>
.distribute-loading {
  height: 60vh;

  margin: 20vh auto;
  width: 400px;
}
.distribute {
  /* height: 80vh; */

  margin: 20vh auto;
  width: 400px;
}
.header {
  margin: 30px 0;
  font-size: 20px;
  text-align: center;
}
</style>
